document.getElementById("speed-2x").addEventListener("click", () => {
  setVideoSpeed(2)
  window.close()
})

document.getElementById("speed-3x").addEventListener("click", () => {
  setVideoSpeed(3)
  window.close()
})

document.getElementById("speed-4x").addEventListener("click", () => {
  setVideoSpeed(4)
  window.close()
})

document.getElementById("seek-time").addEventListener("click", () => {
  seekVideoTime(60)
  window.close()
})

// 增加倍速
document.getElementById("increase-speed").addEventListener("click", () => {
  adjustSpeed(0.1)
})

// 减少倍速
document.getElementById("decrease-speed").addEventListener("click", () => {
  adjustSpeed(-0.1)
})

function setVideoSpeed(speed) {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        func: (speed) => {
          const video = document.querySelector("video")
          if (video) {
            video.playbackRate = speed
          } else {
            alert("当前页面未找到视频元素！")
          }
        },
        args: [speed],
      })
    }
  })
}

function seekVideoTime(time) {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        func: (time) => {
          const video = document.querySelector("video")
          if (video) {
            video.currentTime = time
          } else {
            alert("当前页面未找到视频元素！")
          }
        },
        args: [time],
      })
    }
  })
}

function adjustSpeed(delta) {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        func: (delta) => {
          const video = document.querySelector("video")
          if (video) {
            let newSpeed = video.playbackRate + delta
            newSpeed = parseFloat(newSpeed.toFixed(1)) // 处理精度丢失
            if (newSpeed > 5) newSpeed = 5 // 限制最大倍速为 5x
            if (newSpeed < 0.1) newSpeed = 0.1 // 限制最小倍速为 0.1x
            video.playbackRate = newSpeed // 设置视频倍速
          } else {
            alert("当前页面未找到视频元素！")
          }
        },
        args: [delta],
      })
    }
  })
}
